<?php
class CategoriesController extends AppController {
    var $name = 'Categories';
    
    var $components = array('RequestHandler','Security','Image');
    
    var $allowed_files=array('image/jpeg','image/gif','image/png','image/jpg');         
    
    
      function beforeFilter(){
          parent::beforeFilter();
          
            /*$options = array(
                'conditions' => array('NOT' => array('id' => array(0))),
                'recursive' => 0,
                'fields' => array('id','name'),
                'order' => array('lft' => 'ASC'),
            );
            
            $parents = $this->Category->find('list', $options);
            
            
            
            
            $parents[1]='Root Category';
            
            $this->set(compact('parents'));
            */
            
            // ensure our ajax methods are posted
            $this->Security->requirePost('getnodes', 'reorder', 'reparent');
              
      }
    
      function admin_add() {
         
            
    
        if(!empty($this->data)):
        
            /*if(!$this->data['Category']['banner']['error'] && !in_array($this->data['Category']['banner']['type'],$this->allowed_files)){
                $this->Session->setFlash('File Upload Error: Invalid file type for banner!');     
                $this->redirect($this->referer());
            }
            else {
            */
            
            $this->data['Category']['created'] = date('Y-m-d H:i:s');
            $this->data['Category']['modified'] = date('Y-m-d H:i:s');
            
            
            /*$file_id = $this->Image->upload_image_and_thumbnail($this->data['Category']['banner'], 540, 73, 'category_banner', 'resize');
                
                  
            if($file_id) :
                $this->data['Category']['banner']=$file_id;
            else:
                unset($this->data['Category']['banner']);
            endif;
            */
        
            if($this->Category->save($this->data)) :
            
                $this->Session->write('Success',true);
                $this->Session->setFlash('Category Saved');
                
                Cache::delete('front_menu', 'news');
                
                $this->redirect(array('controller' => 'categories','action'=>'index'));
                exit;
            endif;
            /*}*/
            
        endif;
        
         
        
        
    }
    
    
    function admin_edit($id) {
      
        
        $this->Category->id = (int)$id;
        if(!empty($this->data)):
            /*if(!$this->data['Category']['banner']['error'] && !in_array($this->data['Category']['banner']['type'],$this->allowed_files)){
                $this->Session->setFlash('File Upload Error: Invalid file type for banner!');     
                $this->redirect($this->referer());
            }
            else {
                
            
            $file_id = $this->Image->upload_image_and_thumbnail($this->data['Category']['banner'], 540, 73, 'category_banner', 'resize');
                
            if($file_id) :
                $this->data['Category']['banner']=$file_id;
            else:
                unset($this->data['Category']['banner']);
            endif;
        
            */
            $this->data['Category']['modified'] = date('Y-m-d H:i:s');
            
            
            
            if($this->Category->save($this->data)) :
                $this->Session->write('Success',true);
                $this->Session->setFlash('Category Saved');
                Cache::delete('front_menu', 'news');
                $this->redirect(array('controller' => 'categories', 'action' => 'index'));
                exit;
            endif;
            /*}*/
        else:
            $this->data = $this->Category->read();
        endif;         
        
        $this->render('admin_add');
        
    }
    
     function admin_delete($id) {
        if($id == null) $this->redirect($this->referer());
        
      
        
        $this->Category->id=(int)$id;
        if($this->Category->delete()) :
            Cache::delete('front_menu', 'news');
            $this->Session->write('Success',true);
            $this->Session->setFlash('Category Deleted Successully');
            
        endif;
        
        $this->redirect($this->referer());
        exit;
    }
    
    
    
    
    function admin_index() {
        
        
        $this->paginate['Category'] = array('recursive' => -1,'conditions' => array(),'order'=>'lft asc');
        
        $cats = $this->paginate('Category');
        
        $categories=array();
        
        foreach($cats as $c){
            $t=$c;
            $t['Category']['parent']=$this->Category->find('first',array('fields'=>array('name'),'recursive'=>-1,'conditions'=>array('id'=>$c['Category']['parent_id'])));
            $categories[]=$t;
        }
        

        $this->set('categories', $categories);

    }
    
    // depricated. i have used it before i implemented the re-order.
    function admin_rebuild_tree($parent, $left) {
       
        
        $right = $left + 1;   

        $options = array(
            'conditions' => array(
                'parent_id' => $parent,
            ),
            'fields' => array('id'),
            'order' => array('id' => 'ASC'),
            );
        
        $this->Category->recursive = -1;
        $children = $this->Category->find('all', $options);
        if($children) :
            foreach($children as $item) :
                $right = $this->admin_rebuild_tree($item['Category']['id'], $right);
            endforeach;
        endif;
        
        $this->Category->updateAll(
            array(
                'lft' => $left,
                'rght' => $right,
            ),
            array(
                'id' => $parent,
            )
        );
        
        Cache::delete('front_menu', 'news');
                   
        return $right + 1;
    }
    
    
    function admin_tree(){
        
    }
    
    
    
    
    
    
    function admin_getnodes() {
        
        
        $this->layout='admin/ajax_category';
        
        // retrieve the node id that Ext JS posts via ajax
        $parent = intval($this->params['form']['node']);
        
        // find all the nodes underneath the parent node defined above
        // the second parameter (true) means we only want direct children
        $nodes = $this->Category->children($parent, true);
        
        // send the nodes to our view
        $this->set(compact('nodes'));
        
    }
    
    function admin_reorder() {
        
        // retrieve the node instructions from javascript
        // delta is the difference in position (1 = next node, -1 = previous node)
        
        $node = intval($this->params['form']['node']);
        $delta = intval($this->params['form']['delta']);
        
        if ($delta > 0) {
            $this->Category->movedown($node, abs($delta));
        } elseif ($delta < 0) {
            $this->Category->moveup($node, abs($delta));
        }
        
        
        
        // send success response
        exit('1');
        
    }
    
    function admin_reparent(){
        
        $node = intval($this->params['form']['node']);
        $parent = intval($this->params['form']['parent']);
        $position = intval($this->params['form']['position']);
        
        // save the employee node with the new parent id
        // this will move the employee node to the bottom of the parent list
        
        $this->Category->id = $node;
        $this->Category->saveField('parent_id', $parent);
        
        // If position == 0, then we move it straight to the top
        // otherwise we calculate the distance to move ($delta).
        // We have to check if $delta > 0 before moving due to a bug
        // in the tree behaviour (https://trac.cakephp.org/ticket/4037)
        
        if ($position == 0) {
            $this->Category->moveup($node, true);
        } else {
            $count = $this->Category->childcount($parent, true);
            $delta = $count-$position-1;
            if ($delta > 0) {
                $this->Category->moveup($node, $delta);
            }
        }
        
        Cache::delete('front_menu', 'news');
        // send success response
        exit('1');
        
    } 
    
    
    
   
    
}
?>